package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.operator.Contain;
import com.ejlchina.searcher.operator.Equal;
import com.ejlchina.searcher.util.MapUtils;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.ServiceException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import com.sky.utils.BeanCopyUtil;
import com.sky.utils.DateUtils;
import com.sky.web.page.TableSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private BeanSearcher beanSearcher;

    /**
     * 员工登录
     *
     * @param dto 用户登陆信息
     * @return
     */
    public Employee login(EmployeeDTO dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();

        Map<String, Object> build = MapUtils.builder()
                .field(Employee::getUsername,username).op(Equal.class)
                .build();
        //1、根据用户名查询数据库中的数据
        Employee employee = beanSearcher.searchFirst(Employee.class, build);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (Objects.isNull(employee)) {
            //账号不存在
            throw new ServiceException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new ServiceException(MessageConstant.PASSWORD_ERROR);
        }
        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new ServiceException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    /**
     * 查询员工
     * @param dto 员工信息
     * @return
     */
    @Override
    public SearchResult<Employee> searchPage(EmployeeDTO dto) {
        Map<String, Object> build = MapUtils.builder()
                .page(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize())
                .field(Employee::getName,dto.getName()).op(Contain.class)
                .orderBy(Employee::getId).asc()
                .build();
        SearchResult<Employee> search = beanSearcher.search(Employee.class, build);
        List<Employee> dataList = search.getDataList();
        if(!CollectionUtils.isEmpty(dataList)){
            dataList.forEach(item ->{
                item.setPassword("******");
            });
        }
        return search;
    }

    /**
     * 根据id查询员工信息
     * @param id 员工id
     * @return
     */
    @Override
    public Employee selectEmployeeById(Long id) {
        Map<String, Object> build = MapUtils.builder()
                .field(Employee::getId,id).op(Equal.class)
                .build();
        Employee employee = beanSearcher.searchFirst(Employee.class, build);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 添加员工信息
     * @param dto 员工信息
     * @return
     */
    @Override
    public int insertEmployee(EmployeeDTO dto) {
        Employee employee = new Employee();
        BeanCopyUtil.copyProperties(dto,employee);
        String password = PasswordConstant.DEFAULT_PASSWORD;
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(password);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateBy(BaseContext.getCurrentUserName());
        employee.setCreateTime(DateUtils.getNowDate());
        employee.setUpdateBy(BaseContext.getCurrentUserName());
        employee.setUpdateTime(DateUtils.getNowDate());
        return employeeMapper.insert(employee);
    }

    /**
     * 修改员工
     * @param dto 员工信息
     * @return
     */
    @Override
    public int updateEmployee(EmployeeDTO dto) {
        Employee employee = new Employee();
        BeanCopyUtil.copyProperties(dto, employee);
        employee.setUpdateBy(BaseContext.getCurrentUserName());
        employee.setUpdateTime(DateUtils.getNowDate());
        return employeeMapper.updateById(employee);
    }

    /**
     * 员工修改密码
     * @param dto 员工信息
     * @return
     */
    @Override
    public int editPassword(PasswordEditDTO dto) {
        int result = 0;
        String oldPassword = dto.getOldPassword();
        String newPassword = dto.getNewPassword();
        Long empId = BaseContext.getCurrentId();
        Map<String, Object> build = MapUtils.builder()
                .field(Employee::getId,empId).op(Equal.class)
                .build();
        Employee employee = beanSearcher.searchFirst(Employee.class, build);
        if (employee != null){
            if (employee.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
                employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
                result = baseMapper.updateById(employee);
            }else {
                result = 2;
            }
        }
        return result;
    }


    @Override
    public int deleteEmployeeById(Long[] ids) {
        UpdateWrapper<Employee> wrapper = new UpdateWrapper<>();
        wrapper.in("id",(Object[]) ids);
        wrapper.set("del_flag","2");
        wrapper.set("update_time", DateUtils.getNowDate());
        wrapper.set("update_by", BaseContext.getCurrentUserName());
        return employeeMapper.update(null,wrapper);
    }
}
